package baidu

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/text/gstr"
	"github.com/gogf/gf/v2/util/gconv"
	"wxgf/library/easyHttp"
)

const generalBasicPath = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"
const generalPath = "https://aip.baidubce.com/rest/2.0/ocr/v1/general"

type GeneralBasicResult struct {
	WordsResult []struct {
		Words string `json:"words"`
	} `json:"words_result"`
	WordsResultNum int    `json:"words_result_num"`
	LogId          int    `json:"log_id"`
	ErrorCode      int    `json:"error_code"`
	ErrorMsg       string `json:"error_msg"`
}

type GeneralResult struct {
	WordsResult []struct {
		Words    string `json:"words"`
		Location struct {
			Top    int `json:"top"`
			Left   int `json:"left"`
			Width  int `json:"width"`
			Height int `json:"height"`
		} `json:"location"`
		VertexesLocation []struct {
			X int `json:"x"`
			Y int `json:"y"`
		} `json:"vertexes_location"`
		FinegrainedVertexesLocation []struct {
			X int `json:"x"`
			Y int `json:"y"`
		} `json:"finegrained_vertexes_location"`
		MinFinegrainedVertexesLocation []struct {
			X int `json:"x"`
			Y int `json:"y"`
		} `json:"min_finegrained_vertexes_location"`
	} `json:"words_result"`
	WordsResultNum int    `json:"words_result_num"`
	LogId          int    `json:"log_id"`
	ErrorCode      int    `json:"error_code"`
	ErrorMsg       string `json:"error_msg"`
}

type ocr struct {
}

func (ocr) GeneralBasic(ctx context.Context, resource string) (*GeneralBasicResult, error) {
	token, err := getToken()
	if err != nil {
		return nil, err
	}
	url := generalBasicPath + "?access_token=" + token
	_, body, err := easyHttp.Ctx(ctx).
		SetHeader("Content-Type", "application/x-www-form-urlencoded").
		Post(url, g.Map{"url": gstr.Trim(resource)})
	if err != nil {
		return nil, err
	}

	var res *GeneralBasicResult
	gconv.Struct(body, &res)
	if res == nil {
		return nil, fmt.Errorf("response nil, body=%s", body)
	}
	if res.ErrorMsg != "" {
		return nil, fmt.Errorf("request error, body=%s", body)
	}

	return res, nil

}

func (ocr) General(ctx context.Context, resource string) (*GeneralResult, error) {
	token, err := getToken()
	if err != nil {
		return nil, err
	}
	url := generalPath + "?access_token=" + token
	_, body, err := easyHttp.Ctx(ctx).
		SetHeader("Content-Type", "application/x-www-form-urlencoded").
		Post(url, g.Map{"url": gstr.Trim(resource), "vertexes_location": "true"})
	if err != nil {
		return nil, err
	}

	var res *GeneralResult
	gconv.Struct(body, &res)
	if res == nil {
		return nil, fmt.Errorf("response nil, body=%s", body)
	}
	if res.ErrorMsg != "" {
		return nil, fmt.Errorf("request error, body=%s", body)
	}

	return res, nil

}
